--[[

Copyright (c) 2012-2013 Baby-Bus.com

http://www.babybus.com/superdo/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

]]

--[[--

场景层类，定义层相关操作方法及逻辑实现。

-   定义场景层功能方法。

]]

----------------------
-- 类
----------------------
local M = classLayerTouch("Main")

----------------------
-- 公共参数
----------------------





----------------------
-- 构造方法
----------------------
--[[--

构造方法，定义视图实例初始化逻辑

### Parameters:
-   table **params**    参数集合

### Return: 
-   object              对象实例

]]
function M:ctor(params)
    -- [参数赋值]
    params = totable(params)


    self.radio_ = V.width/960
  
end








----------------------
-- 结点渲染
----------------------
--[[--

视图渲染，处理视图结点加载、事件绑定等相关操作

]]
function M:onRender()
    -- [超类调用]
    M.super.onRender(self)

    sound.playMusic("g/boxbg.mp3")



    self:loadUI()

    -- 加载渲染以外的其他操作
    self:loadRenderOtherwise()
end

-- 加载渲染以外的其他操作
function M:loadRenderOtherwise()
    self.panda:play("qiqi_",20/60)
    A.cycle({
        {"delay",1.8},
        {"scaleTo",0.2,1.1},
        {"scaleTo",0.2,1},
        {"scaleTo",0.2,1.1},
        {"scaleTo",0.2,1},
        {"delay",0.5},
    }):at(self.button)
end

function M:loadUI()
    local bg = D.img("g/ui4/bg.png"):p(0,0):to(self):anchor(ccp(0,0)):scale(self.radio_)

    local tree = D.img("g/ui4/tree.png"):p(V.fullSize.width+24,V.fullSize.height+53):to(self):anchor(ccp(1,1)):scale(V.fullRatio):bindTouch()
    self:loadPanda(tree)
    self:loadBird(tree)
    self:loadButton(tree)
    self:loadIcons()
end

function M:loadButton(parent)
    local button = D.img("g/ui4/btn_play.png"):p(260,-200):to(parent)
    button:bindTouch()
    button.canTouch = true
    function button:onTouchBegan(x,y,touches)
        sound.playSound("g/tap.mp3")
        if not self.canTouch then
            return false
        else
            return true
        end
    end
    function button:onTouchEnded(x,y,touches)
        if TH.isTouchInsideAndVisible(self, x, y, true) then
            self.canTouch = false
            A.line({
                {"delay",0.2},
                {"fn",function ( ... )
                    sound.stopMusic()

                    
                    self:getScene():switchNextScene()
                end}
            }):at(self)
        end
    end
    self.button = button
end
function M:getAppInfo()
    --     "adID": "com.sinyee.babybus.soda",
    -- "adType": "default",
    -- "appKey": "com.sinyee.babybus.soda",
    -- "appLink": "https://play.google.com/store/apps/details?id=com.sinyee.babybus.soda",
    -- "appName": "宝宝果汁商店",
    -- "ident": "6128aa4ee4eeaae9",
    -- "localImagePath": "res/img/xx/g/recommend/en/home_re/com.sinyee.babybus.soda.png",
    -- "showNum": "2",
    -- "updateTime": "-1"
    local data = NV.getADData(19)
    local result = {}
    if istable(data) and next(data) then
        for i,v in ipairs(data) do
            local info = v
            info.appKey     = v.appKey
            info.appName    = v.appName
            info.localImagePath       = v.localImagePath
            info.appLink       = v.appLink
            info.showNum    = v.showNum
            info.updateTime = v.updateTime
            info.ident      = v.ident
            info.adID       = v.adID
            info.adType     = v.adType

            if not NV.isAppInstalled(v.appKey) then
                table.insert(result,v)
            end
        end
    end


    if ismac() then
        result = {
            {
                ["appKey"]      = "com.sinyee.babybus.recommendapp",
                ["appName"]     = "宝宝巴士大全",
                ["localImagePath"]        = "g/recommend/com.sinyee.babybus.egg.png",
                ["appLink"]        = "",
                ["showNum"]     = "",
                ["updateTime"]  = "",
                ["ident"]       = "",
                ["mediatype"]   = "",
                ["adID"]        = "",
            },
            {
                ["appKey"]      = "com.sinyee.babybus.recommendapp",
                ["appName"]     = "宝宝巴士大全",
                ["localImagePath"]        = "g/recommend/com.sinyee.babybus.egg.png",
                ["appLink"]        = "",
                ["showNum"]     = "",
                ["updateTime"]  = "",
                ["ident"]       = "",
                ["mediatype"]   = "",
                ["adID"]        = "",
            },
            {
                ["appKey"]      = "com.sinyee.babybus.recommendapp",
                ["appName"]     = "宝宝巴士大全",
                ["localImagePath"]        = "g/recommend/com.sinyee.babybus.egg.png",
                ["appLink"]        = "",
                ["showNum"]     = "",
                ["updateTime"]  = "",
                ["ident"]       = "",
                ["mediatype"]   = "",
                ["adID"]        = "",
            },
            {
                ["appKey"]      = "com.sinyee.babybus.recommendapp",
                ["appName"]     = "宝宝巴士大全",
                ["localImagePath"]        = "g/recommend/com.sinyee.babybus.egg.png",
                ["appLink"]        = "",
                ["showNum"]     = "",
                ["updateTime"]  = "",
                ["ident"]       = "",
                ["mediatype"]   = "",
                ["adID"]        = "",
            },
            {
                ["appKey"]      = "com.sinyee.babybus.recommendapp",
                ["appName"]     = "宝宝巴士大全",
                ["localImagePath"]        = "g/recommend/com.sinyee.babybus.egg.png",
                ["appLink"]        = "",
                ["showNum"]     = "",
                ["updateTime"]  = "",
                ["ident"]       = "",
                ["mediatype"]   = "",
                ["adID"]        = "",
            },
            {
                ["appKey"]      = "com.sinyee.babybus.recommendapp",
                ["appName"]     = "宝宝巴士大全",
                ["localImagePath"]        = "g/recommend/com.sinyee.babybus.egg.png",
                ["appLink"]        = "",
                ["showNum"]     = "",
                ["updateTime"]  = "",
                ["ident"]       = "",
                ["mediatype"]   = "",
                ["adID"]        = "",
            },
            {
                ["appKey"]      = "com.sinyee.babybus.recommendapp",
                ["appName"]     = "宝宝巴士大全",
                ["localImagePath"]        = "g/recommend/com.sinyee.babybus.egg.png",
                ["appLink"]        = "",
                ["showNum"]     = "",
                ["updateTime"]  = "",
                ["ident"]       = "",
                ["mediatype"]   = "",
                ["adID"]        = "",
            },
            {
                ["appKey"]      = "com.sinyee.babybus.recommendapp",
                ["appName"]     = "宝宝巴士大全",
                ["localImagePath"]        = "g/recommend/com.sinyee.babybus.egg.png",
                ["appLink"]        = "",
                ["showNum"]     = "",
                ["updateTime"]  = "",
                ["ident"]       = "",
                ["mediatype"]   = "",
                ["adID"]        = "",
            },
            {
                ["appKey"]      = "com.sinyee.babybus.recommendapp",
                ["appName"]     = "宝宝巴士大全",
                ["localImagePath"]        = "g/recommend/com.sinyee.babybus.egg.png",
                ["appLink"]        = "",
                ["showNum"]     = "",
                ["updateTime"]  = "",
                ["ident"]       = "",
                ["mediatype"]   = "",
                ["adID"]        = "",
            },
        }
    end

    return result
end

function M:loadIcons()
    local info = self:getAppInfo()
    local center = ccp(290,V.fullSize.height/2)
    local bg = D.imgsz("g/ui4/mask.png",CCSize(400*self.radio_,417*V.fullRatio)):p(center.x*self.radio_,center.y):to(self,99)
    local ad = D.imgsz("g/open/ad_en.png", CCSize(27,16)):p(10,15):anchor(ccp(0,0)):to(bg,100)
    for i=0,8 do
        local appInfo = info[i+1]
        if not appInfo then
            break
        end
        local x = (i%3-1)*(125*V.fullRatio+2.5)
        local y = (math.floor(i/3)-1)*125*V.fullRatio
        local radio = 1
        local item = D.imgsz(appInfo.localImagePath, CCSize(90*radio*V.fullRatio,90*radio*V.fullRatio)):p((center.x+x)*self.radio_,center.y-y):to(self,100)

        local str = "在线配置"
        if appInfo.adType == "default" then
            str = "默认配置"
        end
        -- 公共统计-开屏9图标-展示次数
        NV.recordEvent(aiolos_inter_firstscene_show_times,appInfo.appKey,str)

        -- 黑名单展示写入
        NV.writeShowTime({
            key = "selfad_19_"..appInfo.ident,
            updateTime = appInfo.updateTime,
            showNum = appInfo.showNum,
        })



        -- D.imgsz("g/ui4/icon_shadow.png", CCSize(285,285)):p(-7,-20):to(item,-1):anchor(ccp(0,0))
        item.info = appInfo
        self:bindItemTouch(item)
    end
end

function M:bindItemTouch(item)
    item:bindTouch({
        pnCool      = true,
        coolTime    = 1,
    })
    item.scaleNum = item:getScale()
    function item:onTouchBegan(x,y,touches)
        sound.playSound("g/tap.mp3")
        self:scale(self.scaleNum*1.1)
        return true
    end
    function item:onTouchEnded(x,y,touches)
        self:scale(self.scaleNum)
        if TH.isTouchInsideAndVisible(self, x, y, true) then
            local info = item.info
            

            if NT.isInternetConnectionAvailable() then
                local str = "在线配置"
                if info.adType == "default" then
                    str = "默认配置"
                end
                -- 公共统计-开屏9图标-展示次数
                NV.recordEvent(aiolos_inter_firstscene_click_times,info.appKey,str)

                NV.openLink(info.appLink,true,info.appKey,info.appName,"900_首屏9图标")
            else
                box.audio.soundNoWifi()
                local currenscene = self:getScene()
                if currenscene then
                    local networkLayer = bb.ui.FNoNetWorkLayer.new()
                    networkLayer:p(0, 0):to(currenscene, ZORDER_MAX + 1)
                end    
            end   
        end     
    end
end

function M:loadPanda(parent)
    bb.si.DragonBone.addFile("g/ui4/qiqi_")
    local armature = bb.si.DragonBone.createArmature("qiqi"):to(parent,10):p(260,493)
    -- local armature = bb.si.DragonBone.createArmature("qiqi",{
    --     movementHandler = function (__evtType, __moveId)
    --         print(__evtType, __moveId)
    --     end
    -- }):to(parent,10):p(260,493)
    self.panda = armature
end

function M:loadBird(parent)
    local bird = D.img("g/ui4/bird_1.png"):p(160,-27):to(parent,100)
    local heart = D.img("g/ui4/heart.png"):p(88,110):to(bird)
    A.cycle({
        { "easing", "SINEINOUT", {"moveBy",1.5,ccp(0,15)} },
        { "easing", "SINEINOUT", {"moveBy",1.5,ccp(0,-15)} },
    }):at(bird)
    A.cycle({
        {"image","g/ui4/bird_",7,1/7},
    }):at(bird)
    local t = 1.5
    A.cycle({
        { "SinTo", t, ccp(128,150), 7, 2},
        {"fn",function ( )
            heart:p(88,110)
        end},
        {"delay",1},
        {"fn",function ( )
            heart:setOpacity(255)
            heart:setScale(1)
        end},
    }):at(heart)
    A.cycle({
        {"fadeOut", t},
        {"delay",1},
    }):at(heart)
    A.cycle({
        {"scaleTo", t, 0.2},
        {"delay",1},
    }):at(heart)
end
----------------------
-- 触控操作
----------------------
--[[--

绑定触控事件[触控开始]

### Example:

### Parameters:
-   number **x**        触控点x(参考系：屏幕)
-   number **y**        触控点y(参考系：屏幕)
-   table **touches**   触控点集合(多点触控时需要)

### Return: 
-   bool                事件结果标识(真：接受点击，否：跳过处理)

--]]--
function M:onTouchBegan(x, y, touches)
    return true
end

--[[--

绑定触控事件[触控结束]

### Example:

### Parameters:
-   number **x**        触控点x(参考系：屏幕)
-   number **y**        触控点y(参考系：屏幕)
-   table **touches**   触控点集合(多点触控时需要)

### Return: 
-   bool                事件结果标识(真：接受点击，否：跳过处理)

--]]--
function M:onTouchEnded(x, y, touches)
    -- -- [操作变量]
 
end














----------------------
-- 结点析构
----------------------
--[[--

视图析构，处理视图结点卸载、事件解除绑定等相关操作

]]
function M:onDestructor()
    -- [超类调用]
    M.super.onDestructor(self)

    -- [本类调用]
end








----------------------
-- 辅助方法
----------------------


return M